<?php
namespace Topxia\Service\Order\OrderProcessor;

use Topxia\Service\Common\ServiceKernel;
use Topxia\Common\NumberToolkit;
use Exception;

class CourseOrderProcessor extends BaseProcessor implements OrderProcessor
{
	protected $router = "course_show";

	public function getRouter() {
		return $this->router;
	}

    public function preCheck($targetId, $userId)
    {
        if ($this->getCourseService()->isCourseStudent($targetId, $userId)) {
            return array('error' => '已经是课程的学员了!');
        }
        $course = $this->getCourseService()->getCourse($targetId);
         if(!$course['buyable']){
            return array('error'=>'该课程不可购买，如有需要，请联系客服');
        }
        if( $course['status'] != 'published') {
            return array('error' =>'不能加入未发布课程!');
        }

        if($course["type"] == "live" && $course["studentNum"] >= $course["maxStudentNum"]) {
            return array('error' => '名额已满，不能加入!');
        }

        return array();
    }

	public function getOrderInfo($targetId, $fields)
	{
		$course = $this->getCourseService()->getCourse($targetId);
		
	//caoqian
	
		@$tags = $course['tags'][0];
        // var_dump($course['tags']);die;
        if(empty($course['tags'])){
            $data['category'] = 0;
        }else{
             $data['category'] = $course['tags'][0];
        }
        if(empty($course)) {
            throw new Exception("找不到要购买课程!");
        }

        $users = $this->getUserService()->findUsersByIds($course['teacherIds']);
       
		//caoqian
		//var_dump($users);
		 $data['uid'] = $fields['userId'];
		 $data['cateId'] = $course['categoryId'];
		 //判断已有学习卡是否过期
		 //获取当前时间
		$ntime = time();
        $cards=  $this->getLearningCardService()->getOrderCard($data);
		foreach($cards as $v){
			//获取已有学习卡的使用到期时间
			 $qtime = strtotime('+'.$v['valid'].'Month',$v['rechargetime']);
			if($ntime>$qtime){
				//如果已有学习卡已经过期
				$status = '';
                $status = 4;
				$id = $v['id'];
                $rechargetime = '';
                $rechargetime = $v['rechargetime'];
				$userId = $fields['userId'];
                $info =  $this->getLearningCardService()->updateStatus($status,$id,$userId,$rechargetime);
			}
		}
		$cards=  $this->getLearningCardService()->getOrderCard($data);
        list($coinEnable, $priceType, $cashRate) = $this->getCoinSetting();
        
        $totalPrice = 0;
		
        if(!$coinEnable) {
        	$totalPrice = $course["price"];
        	return array(
				'totalPrice' => $totalPrice,
				'targetId' => $targetId,
            	'targetType' => "course",
				'course' => empty($course) ? null : $course,
				'users' => $users,
        	);
        }

        if ($priceType == "Coin") {
            $totalPrice = $course["coinPrice"];
        } else if($priceType == "RMB") {
			//判断是否打折
			if($course['discountId']!=0){
				 $totalPrice = $course["price"]*($course['discount']/10);
			}else{
				 $totalPrice = $course["price"];
			}
			
			if(isset($fields['isice']) && $fields['isice']){
				$totalPrice = $course['iceprice'];
			}
          
			
			
           if($course['discountId']!='0'){
              $maxCoin = NumberToolkit::roundUp($course['maxRate'] * $course['originPrice'] / 100 * $cashRate*($course['discount']/10));   

            }else{
            $maxCoin = NumberToolkit::roundUp($course['maxRate'] * $course['originPrice'] / 100 * $cashRate);        

            }       
			
		}

        list($totalPrice, $coinPayAmount, $account, $hasPayPassword) = $this->calculateCoinAmount($totalPrice, $priceType, $cashRate,$tags);
		
        if (!isset($maxCoin)) {
            $maxCoin = $coinPayAmount;
        }
        return array(
			'cards' => empty($cards) ? null : $cards,
            'course' => empty($course) ? null : $course,
            'users' => empty($users) ? null : $users,
            'totalPrice' => $totalPrice,
            'targetId' => $targetId,
            'targetType' => "course",
            'cashRate' => $cashRate,
            'priceType' => $priceType,
            'account' => $account,
            'hasPayPassword' => $hasPayPassword,
            'coinPayAmount' => $coinPayAmount,
            'maxCoin' => $maxCoin,
        );
	}

	public function shouldPayAmount($targetId, $priceType, $cashRate, $coinEnabled, $fields)
    {
        $totalPrice = $this->getTotalPrice($targetId, $priceType,$fields['isice']);
        
 
        //曹乾 判断是否打折
      
        if($fields['discountId'] != 0){
			
           $amount = $totalPrice*$fields['discount']/10; 
        }else{
            $amount = $totalPrice;
        }
		if($fields['isice']){
            $amount = $totalPrice;
		}
	     

        //优惠码优惠价格
        $couponApp = $this->getAppService()->findInstallApp("Coupon");
        $couponSetting = $this->getSettingService()->get("coupon");
        if(!empty($couponApp) && isset($couponSetting["enabled"]) && $couponSetting["enabled"] == 1 && $fields["couponCode"] && trim($fields["couponCode"]) != "") {
            $couponResult = $this->afterCouponPay(
                $fields["couponCode"], 
                'course',
                $targetId, 
                $totalPrice, 
                $priceType, 
                $cashRate
            );
            if(isset($couponResult["useable"]) && $couponResult["useable"]=="yes" && isset($couponResult["afterAmount"])){
                $amount = $couponResult["afterAmount"];
            } else {
                unset($couponResult);
            }
        }
		  

        //虚拟币优惠价格
        if(array_key_exists("coinPayAmount", $fields)) {
            $amount = $this->afterCoinPay(
                $coinEnabled, 
                $priceType, 
                $cashRate, 
                $amount,
                $fields['coinPayAmount'], 
                $fields["payPassword"]
            );
        }

        if ($priceType == "Coin") {
            $amount = $amount/$cashRate;
            // var_dump($amount);die;
        }
        if($amount<0){
            $amount = 0;
        }
        
        $totalPrice = NumberToolkit::roundUp($totalPrice);
        // $amount = NumberToolkit::roundUp($amount);





        //caoqian
		if(!empty($fields['cm'])){
			if($fields['cm'] != '0'){
			   $amount = NumberToolkit::roundUp($amount-$fields['cm']);
			   if($amount<= '0'){
					$amount = '0';
			   }
			}
		}else{
            $amount = NumberToolkit::roundUp($amount);

        }


        return array(
            $amount, 
            $totalPrice, 
            empty($couponResult) ? null : $couponResult,
        );
    }

	public function createOrder($orderInfo, $fields) 
	{
		return $this->getCourseOrderService()->createOrder($orderInfo);
	}

    protected function getTotalPrice($targetId, $priceType,$isice = 0)
    {
        $totalPrice = 0;
        $course = $this->getCourseService()->getCourse($targetId);
        if($priceType == "RMB") {
            $totalPrice = $course["price"];
        } else if ($priceType == "Coin") {
            $totalPrice = $course["coinPrice"];
        }
		if($isice){
			$totalPrice = $course["iceprice"];
		}
        $totalPrice = (float)$totalPrice;
        return $totalPrice;
    }

	public function doPaySuccess($success, $order) {
        if (!$success) {
            return ;
        }

	
        $this->getCourseOrderService()->doSuccessPayOrder($order['id']);

        return ;
    }

    protected function getCouponService()
    {
        return ServiceKernel::instance()->createService('Coupon:Coupon.CouponService');
    }

    protected function getAppService()
    {
        return ServiceKernel::instance()->createService('CloudPlatform.AppService');
    }

    protected function getCourseService()
    {
    	return ServiceKernel::instance()->createService('Course.CourseService');
    }

    protected function getSettingService()
    {
        return ServiceKernel::instance()->createService('System.SettingService');
    }

    protected function getUserService()
    {
        return ServiceKernel::instance()->createService('User.UserService');
    }

	protected function getCourseOrderService() {
		return ServiceKernel::instance()->createService("Course.CourseOrderService");
	}
	//caoqian
	   protected function getLearningCardService()
    {
        return  ServiceKernel::instance()->createService('Kuke.LearningCardService');
    }
}